<!-- 这里是接收端,需要启动https服务器打开 -->
<video
  autoplay
  playsinline
  muted
  id="video"
  width="100%"
  height="100%"
  controls
  poster="R-C.jpg"
></video>
<script>
  // 全屏video
  // function enterFullscreen(el) {
  //   if (el.requestFullscreen) {
  //     el.requestFullscreen();
  //   } else if (el.webkitRequestFullscreen) {
  //     el.webkitRequestFullscreen(); // Safari
  //   } else if (el.msRequestFullscreen) {
  //     el.msRequestFullscreen(); // IE
  //   }
  // }

  // 生成一个基于随机数 + 时间戳的简易 ID
  function generateSimpleDeviceId() {
    // 浏览器: 使用 crypto.getRandomValues (或 fallback)
    // Node.js: 使用 crypto.randomBytes
    let u = localStorage.getItem("myscreenkeyid"); // 持久化存储
    if (u) {
      return u;
    }
    const randomPart =
      typeof window !== "undefined" && window.crypto
        ? Array.from(window.crypto.getRandomValues(new Uint8Array(4)))
            .map((b) => b.toString(16).padStart(2, "0"))
            .join("")
        : require("crypto").randomBytes(4).toString("hex");

    // 时间戳部分（简化）
    const timePart = Date.now().toString(36).slice(-6);
    localStorage.setItem("myscreenkeyid", `device-${randomPart}-${timePart}`);
    return `device-${randomPart}-${timePart}`;
  }
  async function getMessageData(msg) {
    let message = "";
    if (msg.data instanceof Blob) {
      const str = await new Response(msg.data).text();
      message = JSON.parse(str);
    } else {
      message = JSON.parse(msg.data);
    }
    return message;
  }
  // 接收端中途加入,创建新的连接;因为webRTC是点对点协议
  function createNewPc(ws) {
    let newpc = new RTCPeerConnection();
    newpc.ontrack = (e) => {
      document.getElementById("video").srcObject = e.streams[0];
      // enterFullscreen(document.getElementById("video")); // 👈 自动进入全屏
    };
    newpc.onicecandidate = (e) => {
      if (e.candidate) {
        ws.send(JSON.stringify({ type: "candidate", data: e.candidate }));
      }
    };
    return newpc;
  }
  const ws = new WebSocket("ws://192.168.3.6:9000");
  const id = generateSimpleDeviceId(); // 当前设备id,不精确但够用
  console.log(id);
  let pc = createNewPc(ws);
  // 连接成功时,获取屏幕共享画面
  ws.onopen = () => {
    ws.send(JSON.stringify({ type: "link", from: id })); // 发送当前设备id
  };
  //   断开wss的连接
  ws.onclose = () => {
    alert("连接已断开");
  };
  ws.onmessage = async (event) => {
    let message = await getMessageData(event);
    if (message.to === id) {
      // 接收 发送端 的 offer，回应 answer
      if (message.type === "offer") {
        await pc.setRemoteDescription(
          new RTCSessionDescription(message.data),
          () => {
            console.log("offer triger setRemoteDescription success!");
          },
          () => {
            console.log("offer triger setRemoteDescription fail!");
          }
        );
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);
        ws.send(JSON.stringify({ type: "answer", data: answer, from: id }));
      } else if (message.type === "candidate") {
        await pc.addIceCandidate(new RTCIceCandidate(message.data));
      }
    }
    if (message.type === "close") {
      alert("屏幕共享已结束");
    } else if (message.type === "restart") {
      ws.send(JSON.stringify({ type: "link", from: id })); // 发送当前设备id
    }
  };
</script>
